package com.musicapp;

import static com.musicapp.Music.currentIndex;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Song extends AppCompatActivity implements Music.ServiceCallbacks {
    private ImageView list;
    private boolean isLike = false;
    private ImageView shoucang;
    private int n = 1;
    private ImageView moshi;
    private ImageView next;
    private ImageView previous;
    List<SongModel> songList = FirstFragment.songList;
    private String lyricurl;
    private ImageView imageView;
    private TextView geci;
    private boolean isImageView = true;
    private SeekBar progressBar;
//    private Handler mHandler = new Handler(Looper.getMainLooper());
    private ImageView exit;
    private boolean isImage1 = true;
    private ImageView play;
    private RotateAnimation rotateAnimation;
    private Music mMusic;
    private boolean mIsBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song);

//        接收数据
        String author = getIntent().getStringExtra("author");
        String image = getIntent().getStringExtra("image");
        String musicname = getIntent().getStringExtra("musicname");
        String musicurl = getIntent().getStringExtra("musicurl");
        lyricurl = getIntent().getStringExtra("lyricurl");

//        判断是否存在歌曲
        SongModel songModel = new SongModel(author,image,musicname,musicurl,lyricurl);
        boolean exists = songList.stream()
                .anyMatch(song -> song.getMusicname().equals(songModel.getMusicname()));
        if (!exists) {
            songList.add(songModel);
        }

//        图像处理
        imageView = findViewById(R.id.songimage);
        Glide.with(imageView.getContext())
                    .load(image)
                    .circleCrop()
                    .into(imageView);
//            rotate
        rotateAnimation = new RotateAnimation(0f,360f,
                Animation.RELATIVE_TO_SELF,0.5f,
                Animation.RELATIVE_TO_SELF,0.5f);
        rotateAnimation.setDuration(5500);
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        rotateAnimation.setInterpolator(new LinearInterpolator());

//      歌曲歌手信息
        TextView textView1 = findViewById(R.id.music);
        textView1.setText(musicname);
        TextView textView2 = findViewById(R.id.author);
        textView2.setText(author);

//        右上角退出
        exit = findViewById(R.id.exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

//        点击播放和暂停
        play = findViewById(R.id.bofang);
        Uri musicUri = Uri.parse(musicurl);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isImage1){
                    if(Music.isPlaying==true){
                        stopMusic();
                    }
                    mMusic.play(musicUri,n);
                    if(isImageView){
                        imageView.startAnimation(rotateAnimation);
                    }
                    play.setImageResource(R.drawable.zanting);
                }else {
                    mMusic.pause();
                    imageView.clearAnimation();
                    play.setImageResource(R.drawable.bofang);
                }
                isImage1 = !isImage1 ;
            }
        });
        Intent intent = new Intent(this, Music.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

//        切歌
        previous = findViewById(R.id.previous);
        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMusic.playPreviousSong(n);
                Glide.with(imageView.getContext())
                    .load(songList.get(currentIndex).getImage())
                    .circleCrop()
                    .into(imageView);
                textView1.setText(songList.get(currentIndex).getMusicname());
                textView2.setText(songList.get(currentIndex).getAuthor());
                play.setImageResource(R.drawable.zanting);
            }
        });
        next = findViewById(R.id.next);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMusic.playNextSong(n);
                Glide.with(imageView.getContext())
                    .load(songList.get(currentIndex).getImage())
                    .circleCrop()
                    .into(imageView);
                textView1.setText(songList.get(currentIndex).getMusicname());
                textView2.setText(songList.get(currentIndex).getAuthor());
                play.setImageResource(R.drawable.zanting);
            }
        });

//        进度条
        progressBar = findViewById(R.id.bar);
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                }else {
                    seekBar.setProgress(mMusic.getCurrent());
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mMusic.pause();
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//                mMusic.seekTo(seekBar.getProgress());
                mMusic.play(musicUri,n);
            }
        });

//        点击图片
        imageView = findViewById(R.id.songimage);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleView();
            }
        });

//        播放模式
        moshi = findViewById(R.id.moshi);
        moshi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (n){
                    case 1:{
                        n = 2;
                        moshi.setImageResource(R.drawable.suiji);
                        break;
                    }
                    case 2:{
                        n = 3;
                        moshi.setImageResource(R.drawable.danqu);
                        break;
                    }
                    case 3:{
                        n = 1;
                        moshi.setImageResource(R.drawable.shunxu);
                        break;
                    }
                }
            }
        });

//        点击收藏
        shoucang = findViewById(R.id.xihuan);
        shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLike){
                    scaleAndRotateAnimation(shoucang, 1.0f, 1.2f, 1.0f, 0f, 360f, 1000);
                    shoucang.setImageResource(R.drawable.xihuan2);
                }else {
                    scaleAnimation(shoucang, 1.0f, 0.8f, 1.0f,1000);
                    shoucang.setImageResource(R.drawable.xihuan);
                }
                isLike = !isLike;
            }
        });

//        点击列表
        list = findViewById(R.id.list);
        list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                com.musicapp.List dialog = new com.musicapp.List(Song.this);
                dialog.show();
            }
        });
    }

    private void scaleAndRotateAnimation(View view, float startScale, float midscale, float endScale, float startRotate, float endRotate, long duration) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", startScale, midscale, endScale);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", startScale, midscale, endScale);
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", startRotate, endRotate);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY, rotate);
        animatorSet.setDuration(duration);
        animatorSet.start();
    }

    private void scaleAnimation(View view, float startScale, float midscale,float endScale, long duration) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", startScale, midscale, endScale);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", startScale, midscale, endScale);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.setDuration(duration);
        animatorSet.start();
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Music.LocalBinder binder = (Music.LocalBinder) service;
            mMusic = binder.getService();
            mIsBound = true;
            binder.registerCallbacks(Song.this);
//            int duration = mMusic.getDuration();
//            progressBar.setMax(duration);

//            mMusic.setSeekBarCallback(new Runnable() {
//                @Override
//                public void run() {
//                    progressBar.setProgress(mMusic.getCurrent());
//                }
//            });
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIsBound = false;
        }
    };

    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        if (!isPlaying) {
            play.setImageResource(R.drawable.bofang);
            progressBar.setProgress(0);
        }
    }

    @Override
    public void onPlaybackProgressChanged(int currentPosition) {
        progressBar.setProgress(currentPosition);
    }

//    private void updateSeekBarProgress() {
//        if (mIsBound && mMusic != null) {
//            progressBar.setProgress(mMusic.getCurrent());
//        }
//    }

//    点击切换图片和歌词
    private void toggleView() {
        if (isImageView) {
            // 切换到 TextView
            displayLyrics(lyricurl);
            geci = new TextView(Song.this);
            geci.setTextSize(20);
            geci.setTextColor(Color.WHITE);
            geci.setGravity(Gravity.CENTER);
            imageView.setVisibility(View.GONE);
            imageView.clearAnimation();
            geci.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toggleView();
                }
            });
            ((ViewGroup) imageView.getParent()).addView(geci, imageView.getLayoutParams());
        } else {
            // 切换回 ImageView
            ((ViewGroup) geci.getParent()).removeView(geci);
            imageView.setVisibility(View.VISIBLE);
            if(!isImage1){
                imageView.startAnimation(rotateAnimation);
            }
        }
        isImageView = !isImageView;
    }

//    下载歌词
    private void displayLyrics(String lyricsUri) {
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                String lyricsText = fetchLyricsFromUri(params[0]);
                return lyricsText;
            }
            @Override
            protected void onPostExecute(String lyricsText) {
                geci.setText(lyricsText);
            }
        }.execute(lyricsUri);
    }
    private String fetchLyricsFromUri(String lyricsUri) {
        try {
            URL url = new URL(lyricsUri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();
            } else {
                return "Error fetching lyrics";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "Error fetching lyrics";
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mIsBound) {
            unbindService(mServiceConnection);
            mIsBound = false;
        }
    }

    public void stopMusic() {
        if (mIsBound && mMusic != null) {
            mMusic.stop();
        }
    }
}